import {NextFunction, Request, Response} from "express";
import UsersServices from "@/services/UsersService";
import MomentUtils from "@/utils/momentUtils";
import usersModel from "@/models/UsersModel";
import * as fs from "fs";
import {UserInterface} from "@/interface/UserInterface";
import {send} from "@/utils/responseUtils";

export default class UsersController {
    /**
     * 更新用户
     * @param req
     * @param res
     */
    public async updateUser(req: Request, res: Response){
        const body=req.body
        console.log("body",body)
        if (!body.id){
            return res.send("用户id不能为空")
        }
        const data=await UsersServices.update(body.id,body)
        console.log("data",data)
        send(res,{code:200,data})
    }
    /**
     * 获取用户
     * @param req
     * @param res
     */
    public getUsers(req: Request, res: Response) {
        console.log("req",req.query)
        const query:UserInterface={
            id:req.query.id as string
        }
        UsersServices.get(query).then(users => {
            res.send(users)
        }).catch(error => {
            res.send(error)
        })
    }

    /**
     * 添加用户
     * @param request
     * @param response
     */
    public async createUser(request: Request, response: Response) {
        console.log("createUser=================request.body",request.body)
        UsersServices.create(request.body).then(res => {
            console.log("createUser=================res",res)
            response.send(res)
        })
            .catch(error => {
                console.log("createUser=================error",error)
                response.send(error.message)
            })
    }

    /**
     * 删除用户
     * @param request
     * @param response
     */
    public async deleteUser(request: Request, response: Response){
        console.log("request",request)
        const user=await UsersServices.delete(request.body.id)

        send(response,{code:200,message:user?"删除成功":"删除失败"})
    }

    /**
     * 登录
     * @param request
     * @param response
     */
    public async login(request: Request, response: Response) {
        const body = request.body
        console.log('login----------body',body.accountNumber)
        const user = await usersModel.findOne({where: {accountNumber: body.accountNumber,password:body.password}})
        console.log('login------------user',user)
        if (user){
            send(response,{code:200,data:user})
        }else {
            send(response,{code:404,message:"账号/密码不正确"})
        }
    }
}